package com.indusfo.spc.service.impl;

import com.indusfo.spc.common.pojo.Temporary;
import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.OfflineListMapper;
import com.indusfo.spc.mapper.OfflineMapper;
import com.indusfo.spc.pojo.Offline;
import com.indusfo.spc.pojo.OfflineList;
import com.indusfo.spc.service.OfflineService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.List;

@Service
public class OfflineServiceImpl implements OfflineService {

    private  static  final Logger logger = LoggerFactory.getLogger(BldcServiceImpl.class);

    @Autowired
    private OfflineMapper offlineMapper;

    @Autowired
    private OfflineListMapper offlineListMapper;


    /**
     * 下线信息更新
     *
     * @param offline
     * @return  JSONObject
     */
    @Transient
    @Override
    public JSONObject updateOffline(Offline offline) {
        String remark = offline.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(offline.getOfflineId() == null) {
                throw new ParamsErrorException("请选择要更新的下线信息");
            }
            checkParam(offline, remark);
            List<Temporary> judge = judgeOperation(offline);
            // 调用存储过程
            int row = offlineMapper.updateOffline(offline);
            if(row == 0) {
                throw new ModifyFailedException("数据更新失败！");
            }else {
                for(Temporary temporary :judge){
                    Integer id = temporary.getId();
                    Integer pid = temporary.getPid();
                    String condition = temporary.getCondition();
                    OfflineList offlineList = new OfflineList();
                    offlineList.setOfflineId(offline.getOfflineId());
                    offlineList.setlProId(pid);
                    switch (condition){
                        case "add":
                            offlineList.setDataState(1);
                            offlineListMapper.insertOfflineList(offlineList);
                            break;
                        case "update":
                            offlineList.setOfflineDetailId(id);
                            offlineListMapper.updateByPrimaryKeySelective(offlineList);
                            break;
                        case "del":
                            Long[] offlineListIds = {id.longValue()};
                            offlineListMapper.delteOfflineList(offlineListIds,2);
                            break;
                        default:
                            break;
                    }
                }
            }
            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * wangqi
     *
     * 判断操作
     *
     * @param offline
     * @return
     */
    private List<Temporary> judgeOperation(Offline offline) {
        Integer offlineId = offline.getOfflineId();
        // 前端传输数据
        List<Temporary> list = offline.getList();
        // 数据库数据
        List<Temporary> list1 = offlineListMapper.selectByOfflineId(offlineId);

        List<Temporary> judge= new ArrayList<>();
        List<Temporary> delList= new ArrayList<>();

        for(Temporary ceshi:list){
            Integer id = ceshi.getId();
            if(id==null){
                ceshi.setCondition("add");
                for(Temporary ceshi11:list1){
                    if(ceshi11.getPid().equals(ceshi.getPid())){
                        ceshi.setCondition("no");
                        delList.add(ceshi11);
                        break;
                    }
                }
                judge.add(ceshi);
                continue;
            }
            Integer rid = ceshi.getPid();
            for(Temporary ceshi1:list1){
                Integer id1 = ceshi1.getId();
                if(id.equals(id1)){
                    Integer rid1 = ceshi1.getPid();
                    if(rid.equals(rid1)){
                        delList.add(ceshi1);
                        ceshi.setCondition("no");
                        judge.add(ceshi);
                    }else {
                        delList.add(ceshi1);
                        ceshi.setCondition("update");
                        judge.add(ceshi);
                    }
                }
            }
        }
        list1.removeAll(delList);
        for(Temporary ceshi1:list1){
            ceshi1.setCondition("del");
            judge.add(ceshi1);
        }
        return judge;
    }

    /**
     * 下线信息查询（分页）
     *
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject selectAll(Offline offline) {
        List<Offline> listOffline = null;
        try {
            Integer pagesize = offline.getPagesize();
            Integer pageindex = offline.getPageindex();
            if(pagesize != null && pageindex != null) {
                offline.setIncept(pagesize*(pageindex - 1));
            }
            listOffline = offlineMapper.selectAll(offline);
            if (listOffline.isEmpty()) {
                return JSONObject.oK("查询不到相关数据", listOffline, 0);
            }
            //查询分页总记录数
            int count = offlineMapper.countOffline(offline); //返回查询到的总记录数
            return JSONObject.oK("查询成功", listOffline, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 下线信息新增
     *
     * @param offline
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    @Transient
    public JSONObject insertOffline(Offline offline) {
        offline.setDataState(1);
        String remark = offline.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(offline.getOfflineId() != null) {
                throw new ParamsErrorException("新增时，不能填写id");
            }

            checkParam(offline, remark);

            int	row = offlineMapper.insertOffline(offline);
            Integer offlineId = offline.getOfflineId();
            Long[] proIds = offline.getlProIds();
            if(proIds.length!=0){
                //批量新增  维修下线明细
                int rows =offlineListMapper.insertOfflineListAll(proIds,offlineId);
            }
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败！");
            }
            return JSONObject.oK("新增成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 1 启用  2 删除  3停用 下线信息
     *
     * @param offlineIds
     * @param dataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Transient
    @Override
    public JSONObject deleteOffline(Long[] offlineIds, Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (offlineIds == null) {
                throw new ParamsErrorException("下线工序ID不能为空");
            }
            // 执行存储过程
            int row = offlineMapper.delteOffline(offlineIds, dataState);
            int i = offlineListMapper.delteOfflineListByOfflineId(offlineIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 参数校验
     *
     * @param offline
     * @param vcRemark
     */
    private void checkParam(Offline offline, String vcRemark) {
        if (offline.getOfflineType() !=  1 && offline.getOfflineType() != 2) {
            throw new ParamsErrorException("工序类型错误");
        }
        if (StringUtils.isEmpty(offline.getOfflineName())) {
            throw new ParamsErrorException("请填写下线工序名称");

        }
        if (offline.getOfflineName().getBytes().length > 50) {
            throw new ParamsErrorException("下线工序名称名超过规定长度");
        }
        if (vcRemark.getBytes().length > 100) {
            throw new ParamsErrorException("说明字数超过规定长度");
        }
        // 名称不能重复
        Integer depCounts = offlineMapper.selectOffline(offline);
        if (depCounts !=0) {
            throw new ParamsErrorException("该下线工序已存在");
        }
    }
}
